#!/bin/sh
main() {
 [ $# -eq 0 ] || exit 1
 ME=`basename $0`
 local LOG="/tmp/$ME.$USER.log"
 {
  date "+$ME %Y-%m-%dT%H%M%S"
  main_logged "$@"
 } 2>&1 |
 tee -a "$LOG"
}

main_logged() {
 [ $# -eq 0 ] || exit 1
 local DIR="/home/shared/xmltv_guide"
 mkdir -p "$DIR" || exit 1
 local ALL="$DIR/listings.xml"

 if [ ! -f "$ALL" ] ; then
  echo "need to create from scratch" >&2
  update "$DIR" "$ALL" || exit 1
 else
  date "+%Y %j" |
  {
   read THISYEAR TODAY
   getfileyearday "$ALL" |
   {
    read SAVEDYEAR SAVEDDAY
    [ -n "$SAVEDDAY" ] || exit 1
    if [ "$SAVEDYEAR" = "$THISYEAR" ] ; then
     AGO=`expr $TODAY - $SAVEDDAY`
     if [ "$AGO" -le 1 ] ; then
      return
     fi
    fi
    echo "download updated version" >&2
    update "$DIR" "$ALL" || exit 1
   } || exit 1
  } || exit 1
 fi
}

update() {
 killall `basename "$0"` #minor hack
 local DIR="$1"
 local ALL="$2"
 local TD="/tmp/$ME.$USER.$$"
 mkdir "$TD" || exit 1
 local TM1="$TD/1.tmp"
 local TM2="$TD/2.tmp"
 export PATH=/home/shared/xmltv/bin/:$PATH
 nice tv_grab_huro --days 5 --output "$TM1" || exit 1
 [ `wc -c < "$TM1"` -gt 0 ] || exit 1
 echo "tv_sort" >&2
 nice tv_sort < "$TM1" > "$TM2" || exit 1
 [ `wc -c < "$TM2"` -gt 0 ] || exit 1
 rm -v "$TM1"
 echo "tv_split" >&2
 nice tv_split --output "$TD/day-%Y%m%d.xmltv" < "$TM2" || exit 1
 mv -v "$TM2" "$ALL" || exit 1
 rm -v $DIR/day-*.xmltv
 mv -vt "$DIR" $TD/day-*.xmltv
 rmdir "$TD"
}

getfileyearday() {
 [ $# -ge 1 ] || exit 1
 ls -lgG --time-style='+%Y %j' "$@" |
 cut -d ' ' -f 4,5
}

main "$@"
